package at.rtm.dao;

import at.rtm.domain.Temperature;
import com.google.appengine.api.datastore.*;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * The <code>HRDTemperatureDAOImpl</code> provides crud methods for accessing collecting temperatures.
 */
@Repository
public class HRDTemperatureDAOImpl implements TemperatureDAO {
    @Override
    public void save(Temperature temperature) {
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Entity temperatureEntity = new Entity("Temperature");
        temperatureEntity.setProperty("Calendar", temperature.getCal().getTime());
        temperatureEntity.setProperty("Temperature", temperature.getTemperature());
        Key key = datastore.put(temperatureEntity);
        temperature.setId(key.getId());
    }

    @Override
    public List<Temperature> findAll() {
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Query q = new Query("Temperature");
        q.addSort("Calendar", Query.SortDirection.DESCENDING);
        PreparedQuery pq = datastore.prepare(q);
        List<Temperature> result = new LinkedList<Temperature>();
        Iterable<Entity> iterable = pq.asIterable();
        for (Entity entity : iterable) {
            result.add(new Temperature(entity.getKey().getId(), (Date) entity.getProperty("Calendar"), (Double) entity.getProperty("Temperature")));
        }
        return result;

    }
}
